package com.prj.ufdm.web.config;

import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

import redis.clients.jedis.JedisPoolConfig;


@Configuration
@EnableRedisRepositories
@EnableCaching
public class RedisConfig {
	
	private static final Logger logger = Logger.getLogger(RedisConfig.class);
    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private String port;
    @Value("${redis.password}")
    private String pwd;
    @Value("${redis.database}")
    private String database;
    
    /**
     * redis缓存池配置
     * @return
     */
    public JedisConnectionFactory jedisConnectionFactory(String host, int port, int database,String pwd) {
        JedisPoolConfig jp = new JedisPoolConfig();
        //jp.setMaxIdle(300);
        //jp.setMaxTotal(600);
        //jp.setMaxWaitMillis(1000);
        JedisConnectionFactory jf = new JedisConnectionFactory();
        jf.setPoolConfig(jp);
        jf.setDatabase(database);
        jf.setHostName(host);
        jf.setPassword(pwd);
        logger.info("redis服务器ip=" + jf.getHostName() + "，端口=" + jf.getPort() + "，数据库=" + jf.getDatabase());
        jf.setPort(port);
        jf.setTimeout(20000);
        return jf;
    }

    /**
     * redis缓存池配置
     * @return
     */
    @Bean
    public JedisConnectionFactory sessionConnectionFactory() {
    	
    	Integer intPort = 6379;
    	try {
    		intPort = Integer.parseInt(port);
    	}
    	catch(Exception er) {
    		
    	}
    	Integer intDatabase = 2;
    	try {
    		intDatabase = Integer.parseInt(database);
    	}
    	catch(Exception er) {
    		
    	}
        return this.jedisConnectionFactory(host,intPort,intDatabase,pwd);
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Bean  
    public RedisTemplate redisTemplate(JedisConnectionFactory connectFactory) {  
    	Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisTemplate redisTemplate = new RedisTemplate(); 
        redisTemplate.setConnectionFactory(connectFactory);  
        redisTemplate.setKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate; 
    } 
    
    @SuppressWarnings("rawtypes")
	@Bean("cacheManager")
    @Primary
    public CacheManager cacheManager(RedisTemplate redisTemplate) { 
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        rcm.setUsePrefix(true);
        return rcm;
    }
    
    @SuppressWarnings("rawtypes")
	@Bean("loginCacheManager")
    public CacheManager loginCacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //设置缓存过期时间
        rcm.setDefaultExpiration(600);//秒
        Map<String,Long> expiresMap = new HashMap<String,Long>();
        expiresMap.put("test_catchbale",120L);
        rcm.setExpires(expiresMap);
        return rcm;
    }

}
